package com.demo.api.conf;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author: cja
 * @date: 2019/11/13 19:42
 */
@Configuration
public class WebConf extends WebMvcConfigurerAdapter {

    @Bean
    public FilterRegistrationBean filterRegistrationCorsBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        CorsFilter corsFilter = new CorsFilter();
        filterRegistrationBean.setFilter(corsFilter);
        filterRegistrationBean.setEnabled(true);
        filterRegistrationBean.addInitParameter("allowOrigin", "*");
        filterRegistrationBean.addInitParameter("allowMethods", "GET,POST,PUT,DELETE,OPTIONS");
        filterRegistrationBean.addInitParameter("allowCredentials", "true");
        filterRegistrationBean.addInitParameter("allowHeaders", "Content-Type,X-Token,X-Username,x-auth-token,Authorization");
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(globalInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/**/swagger-ui.html");
    }

    @Bean
    public GlobalInterceptor globalInterceptor() {
        return new GlobalInterceptor();
    }
}
